/*
 * BroadcastSample0.java
 *
 * Created on Mar 2, 2010 12:00:34 AM;
 */

package org.sunspotworld;

import com.sun.spot.core.util.Utils;
import com.sun.spot.espot.service.BootloaderListenerService;
import com.sun.spot.multihop.io.j2me.radiogram.RadiogramConnection;
import java.io.IOException;

import javax.microedition.io.Connector;
import javax.microedition.io.Datagram;
import javax.microedition.io.DatagramConnection;
import javax.microedition.midlet.MIDletStateChangeException;


import javax.microedition.midlet.MIDlet;

/**
 * @author: David Mercier <david.mercier@sun.com>
 *
 * This simple demo shows you how to use the radio to broadcast
 * some data to any listening SPOT(s).
 *
 * There is one thread (startSenderThread) that sends data on a particular
 * channel.
 * There is a second thread (startReceiverThread) that receives
 * data on that same channel.
 *
 */
public class BroadcastSample0 extends MIDlet {

    protected void startApp() throws MIDletStateChangeException {

        System.out.println("I'm about to rock that SPOT !");
        new BootloaderListenerService().getInstance().start();       // Listen for downloads/commands over USB connection

        startSenderThread();
        startReceiverThread();
    }

    /**
     * The receiver thread blocks on the receive function
     * so you don't have to sleep between each receive.
     */
    public void startReceiverThread() {
        new Thread() {
            public void run() {
                String tmp = null;
                RadiogramConnection dgConnection = null;
                Datagram dg = null;

                try {
                    dgConnection = (RadiogramConnection) Connector.open("radiogram://:37");
                    // Then, we ask for a datagram with the maximum size allowed
                    dg = dgConnection.newDatagram(dgConnection.getMaximumLength());
                } catch (IOException e) {
                    System.out.println("Could not open radiogram receiver connection");
                    e.printStackTrace();
                    return;
                }

                while(true){
                    try {
                        dg.reset();
                        dgConnection.receive(dg);
                        tmp = dg.readUTF();
                        System.out.println("Received: " + tmp + " from " + dg.getAddress());
                    } catch (IOException e) {
                        System.out.println("Nothing received");
                    }
                }
            }
        }.start();
    }

    /**
     * The sender thread sends a string each 500 ms
     */
//    synchronized public void startSenderThread() {
        public void startSenderThread() {
        new Thread() {
            public void run() {
                // We create a DatagramConnection
                DatagramConnection dgConnection = null;
                Datagram dg = null;
                try {
                    // The Connection is a broadcast so we specify it in the creation string
                    dgConnection = (DatagramConnection) Connector.open("radiogram://broadcast:37");
                    // Then, we ask for a datagram with the maximum size allowed
                    dg = dgConnection.newDatagram(dgConnection.getMaximumLength());
                } catch (IOException ex) {
                    System.out.println("Could not open radiogram broadcast connection");
                    ex.printStackTrace();
                    return;
                }

                while(true){
                    try {
                        // We send the message (UTF encoded)
                        dg.reset();
                        dg.writeUTF("I rock");
                        dgConnection.send(dg);
                        System.out.println("Broadcast is going through");
                    } catch (IOException ex) {
                        ex.printStackTrace();
                    }
                    Utils.sleep(500);
                }
            }
        }.start();
    }

    protected void pauseApp() {
    }

    /**
     * Called if the MIDlet is terminated by the system.
     * I.e. if startApp throws any exception other than MIDletStateChangeException,
     * if the isolate running the MIDlet is killed with Isolate.exit(), or
     * if VM.stopVM() is called.
     *
     * It is not called if MIDlet.notifyDestroyed() was called.
     *
     * @param unconditional If true when this method is called, the MIDlet must
     *    cleanup and release all resources. If false the MIDlet may throw
     *    MIDletStateChangeException  to indicate it does not want to be destroyed
     *    at this time.
     */
    protected void destroyApp(boolean unconditional) throws MIDletStateChangeException {
    }

}